import logging

from flask import jsonify

from airflow.patsnap.service import user_service
from airflow.models import Pool
from airflow.models.idata_project import Project
from airflow.utils.session import provide_session

log = logging.getLogger(__name__)


@provide_session
def get_pools(page, session: None):
    if page == 0:
        roles = Pool.get_pools(session)
        map_roles = map(Pool.to_json, roles)
        return list(map_roles)
    else:
        role_result = Pool.get_pools_page(page, session)
        role_result.items = list(map(Pool.to_json, role_result.items))
        result = role_result.to_json()
        return result


@provide_session
def delete_pool(pid, session: None):
    # 判断是否有项目在用
    slot_pool = Pool.get_pool_id(pid)
    if slot_pool:
        name = slot_pool.pool
        projects = Project.get_projects(name, session)
        if projects and len(projects) > 0:
            return jsonify(code=500, message='队列还在使用,删除失败!', data=None)
        Pool.delete_pool(pid, session)


def add_pool(name, slots, desc):
    pool = Pool(name, slots, desc)
    Pool.add_pool(pool)


@provide_session
def update_pool(pid, name, slots, desc, session=None):
    slot_pool = Pool.get_pool_id(pid, session)
    if slot_pool:
        projects = Project.get_projects(slot_pool.pool, session)
        if projects and len(projects) > 0 and name != slot_pool.pool:
            return jsonify(code=500, message='队列还在使用,清先修改项目!', data=None)
        pool = Pool(name, slots, desc)
        pool.id = pid
        Pool.update_pool(pool, session)